package com.xinqi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xinqi.common.R;
import com.xinqi.mapper.UserMapper;
import com.xinqi.pojo.bean.User;
import com.xinqi.pojo.vo.LoginVo;
import com.xinqi.pojo.vo.UserInfoVo;
import com.xinqi.service.UserService;
import com.xinqi.util.JwtUtils;
import com.xinqi.util.MD5;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author xin麒
 * @date 2023/1/14 20:33
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public R<User> register(User user) {
        String mobile = user.getMobile();
        if (mobile == null) return R.error("mobile has not given!");
        //检查是否已经注册
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getMobile,mobile);
        User one = getOne(queryWrapper);
        if (one != null) return R.error("this mobile has been register!");
        //检查密码是否为空
        String password = user.getPassword();
        if (password == null) return R.error("password has not given!");
        //隐藏密码
        User userOne = new User();
        userOne.setMobile(mobile);
//        userOne.setPassword(MD5.encrypt(password));
        save(userOne);

        return R.success(userOne);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R<UserInfoVo> login(LoginVo loginVo) {
        String mobile = loginVo.getMobile();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mobile",mobile);
        User one = getOne(queryWrapper);
        if (one == null) return R.error("该用户未注册");
        String password = loginVo.getPassword();
        String encrypt = MD5.encrypt(password);
        if (!one.getPassword().equals(encrypt)) return R.error("密码错误！");

        //通过用户id和电话号码创建token:
        String tokenVal = JwtUtils.createTokenByUserIdAndMobile(one.getId(), one.getMobile());//token的值
        String token = UUID.randomUUID().toString().replaceAll("-", "");//uuid为token前缀
        tokenVal = token + tokenVal;

        UserInfoVo userInfoVo = new UserInfoVo();
        userInfoVo.setMobile(one.getMobile());
        userInfoVo.setToken(tokenVal);



        stringRedisTemplate.opsForValue().set(tokenVal, mobile, 60, TimeUnit.SECONDS);//将用户的ID信息存入redis缓存，并设置60秒的过期时间

        return R.success(userInfoVo);
    }

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

}
